package com.ls.controller;

import com.ls.entity.*;
import com.ls.event.EventProducer;
import com.ls.service.CommentService;
import com.ls.service.DiscussPostService;
import com.ls.service.LikeService;
import com.ls.service.UserService;
import com.ls.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author ls
 */
@Controller
@RequestMapping("/discuss")
public class DiscussPostController implements CommunityConstant {

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private UserService userService;

    @Resource
    private CommentService commentService;

    @Autowired
    private UserContextHolder userContextHolder;

    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 功能描述: <br>
     * 发布帖子
     *
     * @param discussPost
     * @return {@link Object}
     * @author ls
     * @date 2021/8/21 19:16
     */
    @PostMapping("/add")
    @ResponseBody
    public Object addDiscussPost(@RequestBody DiscussPost discussPost) {
        User user = userContextHolder.getUser();
        if (user == null) {
            return CommunityUtil.getJSONString(403, "您还没有登录!");
        }
        discussPost.setUserId(user.getId());
        discussPost.setCreateTime(new Date());
        discussPostService.addDiscussPost(discussPost);

        // 触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(user.getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(discussPost.getId());
        eventProducer.fireEvent(event);

        // 发布帖子, 将帖子id存入redis, 计算帖子热度 分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey, discussPost.getId());

        return CommunityUtil.getJSONString(200, "发布成功");
    }

    @GetMapping("/detail/{discussPostId}")
    public String queryDiscussPost(@PathVariable("discussPostId") int discussPostId, Model model, Page page) {
        // 帖子
        DiscussPost discussPost = discussPostService.queryDiscussPostById(discussPostId);
        model.addAttribute("post", discussPost);
        // 作者
        User user = userService.queryUserById(discussPost.getUserId());
        model.addAttribute("user", user);

        // 帖子点赞数
        long likeCount = likeService.getEntityLikeCount(ENTITY_TYPE_POST, discussPostId);
        model.addAttribute("likeCount", likeCount);
        // 帖子点赞状态
        int likeStatus = userContextHolder.getUser() == null ? 0 :
                likeService.getEntityLikeStatus(userContextHolder.getUser().getId(), ENTITY_TYPE_POST, discussPostId);
        model.addAttribute("likeStatus", likeStatus);

        // 评论分页信息
        page.setPageSize(5);
        page.setPath("/discuss/detail/" + discussPostId);
        page.setTotalCount(discussPost.getCommentCount());

        // 评论: 给帖子的评论
        // 回复: 给评论的评论
        // 评论列表
        List<Comment> commentList = commentService.queryCommentsByEntity(ENTITY_TYPE_POST,
                discussPost.getId(), page.getStartIndex(), page.getPageSize());
        List<Map<String, Object>> commentVoList = new ArrayList<>();
        if (commentList != null) {
            for (Comment comment : commentList) {
                // 评论vo
                Map<String, Object> commentVo = new HashMap<>();
                // 评论
                commentVo.put("comment", comment);
                // 作者
                commentVo.put("user", userService.queryUserById(comment.getUserId()));

                // 评论点赞数
                likeCount = likeService.getEntityLikeCount(ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeCount", likeCount);
                // 评论点赞状态
                likeStatus = userContextHolder.getUser() == null ? 0 :
                        likeService.getEntityLikeStatus(userContextHolder.getUser().getId(), ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeStatus", likeStatus);

                // 回复列表 不对回复列表进行分页从0查到最后
                List<Comment> replyList = commentService.queryCommentsByEntity(ENTITY_TYPE_COMMENT,
                        comment.getId(), 0, Integer.MAX_VALUE);

                // 回复vo
                List<Map<String, Object>> replyVoList = new ArrayList<>();
                if (replyList != null) {
                    for (Comment reply : replyList) {
                        Map<String, Object> replyVo = new HashMap<>();
                        // 回复
                        replyVo.put("reply", reply);
                        // 作者
                        replyVo.put("user", userService.queryUserById(reply.getUserId()));

                        // 回复点赞数
                        likeCount = likeService.getEntityLikeCount(ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.put("likeCount", likeCount);
                        // 回复点赞状态
                        likeStatus = userContextHolder.getUser() == null ? 0 :
                                likeService.getEntityLikeStatus(userContextHolder.getUser().getId(), ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.put("likeStatus", likeStatus);

                        // 回复目标
                        User target = reply.getTargetId() == 0 ? null : userService.queryUserById(reply.getTargetId());
                        replyVo.put("target", target);
                        replyVoList.add(replyVo);
                    }
                }
                commentVo.put("replys", replyVoList);

                // 回复数量
                int replyCount = commentService.queryCountByEntity(ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("replyCount", replyCount);
                commentVoList.add(commentVo);
            }
            model.addAttribute("comments", commentVoList);
        }

        return "/site/discuss-detail";
    }

    /**
     * 功能描述: <br>
     * 帖子置顶
     *
     * @param id
     * @return {@link R}
     * @author ls
     * @date 2021/8/28 19:51
     */
    @PostMapping("/top/{id}")
    @ResponseBody
    public R top(@PathVariable("id") int id) {
        discussPostService.updateType(id, 1);
        // 触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(userContextHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);
        return R.ok();
    }

    /**
     * 功能描述: <br>
     * 加精帖子
     *
     * @param id
     * @return {@link R}
     * @author ls
     * @date 2021/8/28 19:52
     */
    @PostMapping("/wonderful/{id}")
    @ResponseBody
    public R wonderful(@PathVariable("id") int id) {
        discussPostService.updateStatus(id, 1);
        // 触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(userContextHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);

        // 加精, 将帖子id存入redis, 计算帖子热度 分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey, id);

        return R.ok();
    }

    /**
     * 功能描述: <br>
     * 删除帖子
     *
     * @param id
     * @return {@link R}
     * @author ls
     * @date 2021/8/28 19:52
     */
    @DeleteMapping("/{id}")
    @ResponseBody
    public R delete(@PathVariable("id") int id) {
        discussPostService.updateStatus(id, 2);
        // 触发删帖事件
        Event event = new Event()
                .setTopic(TOPIC_DELETE)
                .setUserId(userContextHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);
        return R.ok();
    }

}
